from django.template import Library
from django.utils.safestring import mark_safe
import datetime,time
from django.core.paginator import Paginator
register=Library()
import datetime
@register.simple_tag()
def build_table_row(obj,admin_class):
    eml=""
    for li in admin_class.list_display:
        column_data=admin_class.model._meta.get_field(li)
        if column_data.choices:
            td="<td>%s</td>"%getattr(obj,'get_%s_display'%li)()
            eml +=td
        else:
            if li == 'id':
                td="<td  ><a href='%s/change' actiontag=true >%s</a></td>"%(getattr(obj,li),getattr(obj,li))
                eml +=td
            else:
                td="<td>%s</td>"%getattr(obj,li)
                eml +=td
    return mark_safe(eml)

@register.simple_tag()
def build_filter_ele(filter_column,admin_class):
    colume_obj=admin_class.model._meta.get_field(filter_column)
    sel="<select name=%s>"%filter_column
    try:
        for choices in colume_obj.get_choices():
            selected=""
            if filter_column in admin_class.filter_dict:
                if str(choices[0]) == str(admin_class.filter_dict[filter_column]):
                    selected='selected'
            sel +="<option value=%s %s>%s</option>"%(choices[0],selected,choices[1])
    except Exception:
        sel="<select name=%s__gte>"%filter_column
        if colume_obj.get_internal_type() in ('DateField','DateTimeField'):

            date_obj=datetime.datetime.now()
            date_list=[
                ['','---------'],
                [date_obj,'今天'],
                [date_obj - datetime.timedelta(3),'三天前'],
                [date_obj - datetime.timedelta(7),'一周前'],
                [date_obj - datetime.timedelta(30),'一个月前'],
                [date_obj.replace(month=1,day=1),'本年'],
                ['','所有']
            ]
            for i in date_list:
                selected=''

                date_str='' if not i[0] else "%s-%s-%s"%(i[0].year,i[0].month,i[0].day)
                # print('0000000000000000',date_str)

                if '%s__gte'%filter_column in admin_class.filter_dict:
                    if date_str == admin_class.filter_dict['%s__gte'%filter_column]:
                    # if date_str == admin_class.filter_dict[filter_column]:
                        selected='selected'
                sel +="<option value=%s %s>%s</option>"%(date_str,selected,i[1])
    sel += "</select>"

    return mark_safe(sel)

@register.simple_tag
def page(admin_class,queryset):
    """
     <ul class="pagination">
        <li class="disabled"><a href="#" aria-label="Previous"><span aria-hidden="true"><</span></a></li>
        <li class="active"><a href="#">1 <span class="sr-only">(current)</span></a></li>
        <li class="disabled"><a href="#" aria-label="Previous"><span aria-hidden="true">></span></a></li>
      </ul>
    """
    pag_html="<ul class='pagination'>"
    eml=""
    page_obj=admin_class.p

    #对过滤后的内容分页
    if admin_class.filter_dict:

            for k,v in admin_class.filter_dict.items():
                eml+="&%s=%s"%(k,v)


    #对搜索后的内容进行分页
    search_str=""
    if admin_class.search_fieldd:
        search_str +="&_q=%s"%admin_class.search_fieldd
    #对排序后的进行分页
    sort_str=''
    if admin_class.sort_id:
        sort_str='&_o=%s'%admin_class.sort_id

    if queryset.has_previous():
            pag_html+='<li  ><a href="?p=%s%s%s%s%s%s"><</a></li>'%(int(admin_class.p_num)-1,eml,search_str,search_str,sort_str,sort_str)

    for page in page_obj.page_range:


        if admin_class.p_num == str(page):
            pag_html+='<li class="active" ><a href="?p=%s%s%s%s">%s</a></li>'%(page,eml,search_str,sort_str,page)
        else:
            pag_html+='<li ><a href="?p=%s%s%s%s">%s</a></li>'%(page,search_str,eml,sort_str,page)
    try:
        if queryset.next_page_number():
                pag_html+='<li  ><a href="?p=%s%s%s%s">></a></li>'%(int(admin_class.p_num)+1,eml,search_str,sort_str)
    except Exception:
        pass
    return mark_safe(pag_html)

@register.simple_tag
def order_tag(index,admin_class):
    if admin_class.sort_id:
        print('-----------------sort_id',admin_class.sort_id)
        if abs(int(admin_class.sort_id)) == index:#判断点击的排序列是否为上次相同的列
            sort_id=admin_class.sort_id
            if sort_id.startswith('-'):
                print('hello word')
                sort_id=abs(int(sort_id))
            else:
                sort_id='-%s'%sort_id
            print('------------------current_id',sort_id)
            return mark_safe('%s'%sort_id)
        else:
            sort_id=index
        return mark_safe('%s'%sort_id)
    else:
        return mark_safe('%s'%index)

@register.simple_tag
def sort_tag(admin_class,index):
    eml=''
    if admin_class.sort_id:
        if abs(int(admin_class.sort_id)) == index:
            if admin_class.sort_id.startswith('-'):
                eml='<span class="glyphicon glyphicon-triangle-bottom" aria-hidden="true"></span>'
            else:
                eml='<span class="glyphicon glyphicon-triangle-top" aria-hidden="true"></span>'
        else:
            return ''
        return mark_safe(eml)
    else:
        return ''

@register.simple_tag
def handle_readonly(admin_class,filed_id):
    elm=''

    for field in admin_class.readonly_fields:

        obj=admin_class.model.objects.get(id=int(filed_id))
        tmp='<p>%s:            %s</p>'%(field,getattr(obj,field))
        elm +=tmp
    return mark_safe(elm)

@register.simple_tag
def get_all_data(filed_name,admin_class,form_obj):
    obj=admin_class.model._meta.get_field(filed_name)
    obj_list=set(obj.related_model.objects.all())
    choices_list=set(getattr(form_obj.instance,filed_name).all())
    obj_list2=obj_list-choices_list


    return obj_list2

@register.simple_tag
def get_choices_data(filed_name,admin_class,form_obj):
    selected_data=getattr(form_obj.instance,filed_name).all()
    return selected_data